package hk.m4s.lr.repair.test.ui.goods;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import framework.common.baseui.UeBaseActivity;
import framework.common.cache.CacheManager;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.SearchDetail;
import hk.m4s.lr.repair.test.ui.adapter.SearchGoodsAdapter;
import hk.m4s.lr.repair.test.ui.adapter.SearchGoodsListAdapter;
import hk.m4s.lr.repair.test.ui.adapter.SearchHistoryAdapter;
import hk.m4s.lr.repair.test.utils.NetworkUtils;
import hk.m4s.lr.repair.test.views.DefaultItemDecoration;
import hk.m4s.lr.repair.test.views.RefreshLayout;
import hk.m4s.lr.repair.test.views.recyclerview.EasyRecyclerView;
import hk.m4s.lr.repair.test.views.recyclerview.adapter.OnLoadMoreListener;
import hk.m4s.lr.repair.test.views.recyclerview.adapter.RecyclerArrayAdapter;
import hk.m4s.lr.repair.test.views.recyclerview.swipe.OnRefreshListener;
import me.gujun.android.taggroup.TagGroup;

/**
 * Created by qi.wang on 2017/10/24.
 * 搜索
 */

public class SearchActivity extends UeBaseActivity {
    private LinearLayout tvClear;
    private LinearLayout searchLy;
    private LinearLayout searchReulstLy;
    private ListView lvSearchHistory;
    private EditText search_et_input;
    private ImageView search_iv_delete;
    private TextView all, price, sales_volume, evaluate, screen;
    @Bind(R.id.refresh_layout)
    RefreshLayout mRlRefresh;
    @Bind(R.id.refresh_rv_content)
    RecyclerView mRvSearch;
    private SearchGoodsAdapter searchGoodsAdapter;
    protected int start = 0;
    protected int limit = 20;
    @Bind(R.id.search_tg_hot)
    TagGroup mTagGroup;
    private SearchHistoryAdapter mHisAdapter;
    private List<String> mHisList = new ArrayList<>();
    private String key="";
    private String typeId = "";
    private String type = "0";
    private int pageSize = 20;
    private int pageNum = 1;
    private int priceState = 1;//1价格升2价格
    private int salesState = 3;//3销量升4销量降
    private int envalueState = 5;//5评价升6评价降
    private SearchGoodsListAdapter searchGoodsListAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        hiddenHeader();
        hiddenFooter();
        findBaseView();
    }
    public void findBaseView(){
        tvClear=(LinearLayout)findViewById(R.id.tvClear);
        searchLy=(LinearLayout) findViewById(R.id.searchLy);
        searchReulstLy=(LinearLayout) findViewById(R.id.searchReulstLy);
        lvSearchHistory=(ListView)findViewById(R.id.lvSearchHistory);
        search_et_input=(EditText) findViewById(R.id.search_et_input);
        search_iv_delete=(ImageView) findViewById(R.id.search_iv_delete);
        all = (TextView) findViewById(R.id.all);
        price = (TextView) findViewById(R.id.price);
        sales_volume = (TextView) findViewById(R.id.sales_volume);
        screen = (TextView) findViewById(R.id.screen);
        search_et_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                key=s.toString();
                if(!TextUtils.isEmpty(key)){
                    search_iv_delete.setVisibility(View.VISIBLE);
                }else{
                    search_iv_delete.setVisibility(View.GONE);
                }
            }
        });
        initDatas();
    }

    public void initDatas() {
        visible(mTagGroup,searchLy);
        gone(mRlRefresh,searchReulstLy);
        mHisAdapter = new SearchHistoryAdapter(this, mHisList);
        lvSearchHistory.setAdapter(mHisAdapter);
        lvSearchHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                search(mHisList.get(position));
            }
        });
        searchGoodsAdapter = new SearchGoodsAdapter();
        mRvSearch.setLayoutManager(new LinearLayoutManager(this));
        mRvSearch.addItemDecoration(new DefaultItemDecoration(this));
        initSearchHistory();
    }
    /**
     * 展开SearchView进行查询
     *
     * @param key
     */
    private void search(String key) {
        if (!TextUtils.isEmpty(key)) {
            search_et_input.setText(key);
            saveSearchHistory(key);
        }
    }
    /**
     * 保存搜索记录.不重复，最多保存10条
     *
     * @param query
     */
    private void saveSearchHistory(String query) {
        List<String> list = CacheManager.getInstance().getSearchHistory();
        if (list == null) {
            list = new ArrayList<>();
            list.add(query);
        } else {
            Iterator<String> iterator = list.iterator();
            while (iterator.hasNext()) {
                String item = iterator.next();
                if (TextUtils.equals(query, item)) {
                    iterator.remove();
                }
            }
            list.add(0, query);
        }
        int size = list.size();
        if (size > 10) { // 最多保存20条
            for (int i = size - 1; i >= 10; i--) {
                list.remove(i);
            }
        }
        CacheManager.getInstance().saveSearchHistory(list);
    }
    private void initSearchHistory() {
        List<String> list = CacheManager.getInstance().getSearchHistory();
        mHisAdapter.clear();
        if (list != null && list.size() > 0) {
            tvClear.setVisibility(View.VISIBLE);
            mHisAdapter.addAll(list);
        } else {
            tvClear.setVisibility(View.GONE);
        }
        mHisAdapter.notifyDataSetChanged();
    }
    public void onClick(View v){
        switch (v.getId()){
            case R.id.search_iv_back:
                finish();
                break;
            case R.id.tvClear:
                CacheManager.getInstance().saveSearchHistory(null);
                initSearchHistory();
                break;
            case R.id.search_iv_delete:
                search_et_input.setText("");
                visible(mTagGroup,searchLy);
                gone(mRlRefresh,searchReulstLy);
                searchGoodsAdapter.clear();
                break;
            case R.id.search_iv_search:
                if (!TextUtils.isEmpty(key)) {
                    saveSearchHistory(key);
                }
                gone(mTagGroup,searchLy);
                searchReulstLy.setVisibility(View.VISIBLE);
                mRlRefresh.setVisibility(View.VISIBLE);
                finishBooks();
                break;
            case R.id.all:
                all.setTextColor(Color.parseColor("#ff3b30"));
                price.setTextColor(Color.parseColor("#777777"));
                sales_volume.setTextColor(Color.parseColor("#777777"));
                screen.setTextColor(Color.parseColor("#777777"));
                type = "0";
                typeId = "";
                pageNum = 1;
                //getShop("1");
                break;
            case R.id.price:
                all.setTextColor(Color.parseColor("#777777"));
                price.setTextColor(Color.parseColor("#ff3b30"));
                sales_volume.setTextColor(Color.parseColor("#777777"));
                screen.setTextColor(Color.parseColor("#777777"));
                pageNum = 1;
                if (priceState == 1) {
                    priceState = 2;
                    type = "1";
                    showImage(price, R.mipmap.sort_down);
                    showImage(sales_volume, R.mipmap.sort_upper);
                    showImage(all, R.mipmap.sort_upper);
                } else {
                    priceState = 1;
                    type = "2";
                    showImage(price, R.mipmap.sort_upper);
                    showImage(sales_volume, R.mipmap.sort_upper);
                    showImage(all, R.mipmap.sort_upper);
                }
                // getShop("1");
                break;
            case R.id.sales_volume:
                all.setTextColor(Color.parseColor("#777777"));
                price.setTextColor(Color.parseColor("#777777"));
                sales_volume.setTextColor(Color.parseColor("#ff3b30"));
                screen.setTextColor(Color.parseColor("#777777"));
                pageNum = 1;
                if (salesState == 3) {
                    salesState = 4;
                    type = "3";
                    showImage(sales_volume, R.mipmap.sort_down);
                    showImage(price, R.mipmap.sort_upper);
                    showImage(all, R.mipmap.sort_upper);
                } else {
                    salesState = 3;
                    type = "4";
                    showImage(sales_volume, R.mipmap.sort_upper);
                    showImage(price, R.mipmap.sort_upper);
                    showImage(all, R.mipmap.sort_upper);
                }
                //getShop("1");
                break;
            case R.id.screen:
                all.setTextColor(Color.parseColor("#777777"));
                price.setTextColor(Color.parseColor("#777777"));
                sales_volume.setTextColor(Color.parseColor("#777777"));
                screen.setTextColor(Color.parseColor("#ff3b30"));
                showImage(all, R.mipmap.sort_upper);
                showImage(sales_volume, R.mipmap.sort_upper);
                showImage(price, R.mipmap.sort_upper);
                 startActivityForResult(new Intent(SearchActivity.this, ScreenActivity.class),10086);
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
    public void showImage(TextView myTextview, int resId) {
        Drawable drawable = getResources().getDrawable(resId);//注意查看方法
        // TextView.setCompoundDrawables(Drawable, Drawable, Drawable, Drawable)
        //的注释，要求设置的drawable必须已经通过Drawable.setBounds方法设置过边界参数
        //所以，此种方式下该行必不可少
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        myTextview.setCompoundDrawables(null, null, drawable, null);
    }

    public void finishBooks() {
        List<SearchDetail> books=new ArrayList<>();
        for(int i=0;i<10;i++){
            SearchDetail model=new SearchDetail();
            model.setEnNum("12");
            model.setGoodsEnNum("99%");
            model.setGoodsName("欧美条纹工作裙");
            model.setGoodsPrice("120");
            model.setGoodsSale("9");
            model.setImgUrl("http://wwhjk.122364.jpg");
            books.add(model);
        }
        searchGoodsAdapter.refreshItems(books);
        if (books.size() == 0){
            mRlRefresh.showEmpty();
        }
        else {
            //显示完成
            mRlRefresh.showFinish();
        }
        //加载
        if (!(mRvSearch.getAdapter() instanceof SearchGoodsAdapter)){
            mRvSearch.setAdapter(searchGoodsAdapter);
        }
    }
}
